package com.cch.apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public static final String WEB_ROOT="d:\\SPACE\\ApacheTest\\web";
	 public Processor(Socket socket) {
		 this.socket = socket;
		 try {
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 try {
		in=	socket.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		
		String fileName = parse(in);
		System.out.println("fileName:"+fileName);
		sendFile(fileName);
	}
	public String parse(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName="";
		try {
			String httpMessage = br.readLine();
			String[]content = httpMessage.split(" ");
			if(content.length!=3){
				sendErrorMessage(400, "Client query error");
				return null;
			}
			fileName = content[1];
			System.out.println("code:"+content[0]+",fileName:"+content[1]+",http version:"+content[2]);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return fileName;
	}
	public void sendErrorMessage(int ErrorCode,String ErrorMessage){
		out.println("HTTP/1.0 "+ErrorCode+" "+ErrorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Messag");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:"+ErrorCode+"ErrorMessage:"+ErrorMessage+"</h1>");
		out.println("");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void sendFile(String fileName){
		fileName=Processor.WEB_ROOT+fileName;
		System.out.println("create file form :"+fileName);
		File file = new File(fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File Not Found");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
